(function(window) {
	var magic = {
		detectTime:  500,
		timer:       null,
		silentTime:  900000,
		silentTimer: null,
		jumped:      false
	};

	// 开启检测
	var beginDetect = function() {
		if(!magic.timer)
			magic.timer = window.setInterval(function() {
				$.scriptcam.getMotionParameters();
			}, magic.detectTime);
	};

	// 判断是否跳转
	var onMotion = function() {
		magic.jumped = pf.getActivePage() != 'status';

		arguments;
		if(!magic.jumped && arguments && arguments[0]) {
			// closeDetect();

			// 跳转
			// magic.jumped = true;
			goToQr();
			resetSilent();
		} else if(magic.jumped && arguments && arguments[0]) {
			resetSilent();
		}
	};

	// 重置silent检测
	var resetSilent = function() {
		return;
		window.clearTimeout(magic.silentTimer);
		magic.silentTimer = window.setTimeout(function() {
			// 10秒钟没有操作 跳回到最初
			window.location.href = '/';
		}, magic.silentTime);
	};

	// 关闭检测
	var closeDetect = function() {
		if(magic.timer) {
			window.clearInterval(magic.timer);
			magic.timer = null;
		}
	};

	// support
	var onError = function() {console.log(arguments);};
	var onWebcamReady = function() {console.log(arguments);};

	var init = function() {
		var tpl = '<div id="webcam"></div>';
		$('body').append(tpl);

		$("#webcam").scriptcam(
				{
					onMotion: onMotion,
					width:    320,
					height:   240
				}
			);

		window.setTimeout(beginDetect, 2000);
	};

	window.initMagic = init;
	// $(init);
	// window.beginDetect = beginDetect;
})(window);